package cn.ug.activity.web.controller;

import cn.ug.activity.bean.CouponStatisticsBean;
import cn.ug.activity.bean.GoldShopBean;
import cn.ug.activity.mapper.entity.GoldShop;
import cn.ug.activity.mapper.entity.GoldShopServices;
import cn.ug.activity.service.GoldShopService;
import cn.ug.activity.web.utils.LocationUtil;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("shop")
public class GoldShopController extends BaseController {
    @Autowired
    private GoldShopService goldShopService;
    //todo 百度地图ak
    private static final String MAP_AK = "百度地图ak";

    @GetMapping(value = "/{id}")
    public SerializeObject get(@RequestHeader String accessToken, @PathVariable int id) {
        if(id < 1) {
            return new SerializeObjectError("00000002");
        }
        GoldShop entity = goldShopService.get(id);
        if(null == entity) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, GoldShop shop, String servicesArr) {
        if(null == shop || StringUtils.isBlank(shop.getName())) {
            return new SerializeObjectError("22000121");
        }
        if (StringUtils.isBlank(shop.getStartTime()) || StringUtils.isBlank(shop.getEndTime())) {
            return new SerializeObjectError("22000122");
        }
        if (StringUtils.isBlank(shop.getProvince()) || StringUtils.isBlank(shop.getCity()) || StringUtils.isBlank(shop.getArea()) || StringUtils.isBlank(shop.getAddress())) {
            return new SerializeObjectError("22000123");
        }
        if (StringUtils.isBlank(servicesArr)) {
            return new SerializeObjectError("22000124");
        }
        try {
            List<GoldShopServices> serviceList = JSON.parseArray(servicesArr, GoldShopServices.class);
            shop.setServices(serviceList);
        } catch (Exception e) {
            return new SerializeObjectError("00000002");
        }
        if (StringUtils.isBlank(shop.getHeadImg())) {
            return new SerializeObjectError("22000127");
        }
        if (StringUtils.isBlank(shop.getColumnImg())) {
            return new SerializeObjectError("22000126");
        }
        if (StringUtils.isBlank(shop.getContactMobile())) {
            return new SerializeObjectError("22000125");
        }
        String address  = shop.getProvince()+shop.getCity()+shop.getArea()+shop.getAddress();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("address", address));
        nvps.add(new BasicNameValuePair("output", "json"));
        nvps.add(new BasicNameValuePair("ak", MAP_AK));
        String data = this.invokeHttp("http://api.map.baidu.com/geocoder/v2/", nvps);
        if (StringUtils.isBlank(data)) {
            return new SerializeObjectError("22000128");
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject == null) {
            return new SerializeObjectError("22000128");
        }
        int status = jsonObject.getIntValue("status");
        if (status != 0) {
            return new SerializeObjectError("22000128");
        }
        shop.setLongitude(jsonObject.getJSONObject("result").getJSONObject("location").getBigDecimal("lng"));
        shop.setLatitude(jsonObject.getJSONObject("result").getJSONObject("location").getBigDecimal("lat"));
        shop.setCreateId(LoginHelper.getLoginId());
        shop.setCreateName(LoginHelper.getLoginName());
        if (goldShopService.save(shop)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PutMapping
    public SerializeObject delete(@RequestHeader String accessToken, int id) {
        if(id < 1) {
            return new SerializeObjectError("00000002");
        }
        if (goldShopService.remove(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PutMapping(value = "/status")
    public SerializeObject enable(@RequestHeader String accessToken, Integer status, int id) {
        status = status == null ? 0 : status;
        if(id < 1) {
            return new SerializeObjectError("00000002");
        }
        if (goldShopService.modifyStatus(id, status)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<GoldShop>> list(@RequestHeader String accessToken, Page page, Order order, String name, String province, Integer status, String startTime, String endTime) {
        name = UF.toString(name);
        province = UF.toString(province);
        startTime = UF.toString(startTime);
        endTime = UF.toString(endTime);
        status = status == null ? -1 : status;
        int total = goldShopService.countRecords(name, province, status, startTime, endTime);
        page.setTotal(total);
        if (total > 0) {
            List<GoldShop> list = goldShopService.listRecords(name, province, status, startTime, endTime, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoldShop>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GoldShop>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GoldShop>()));
    }

    @GetMapping(value = "/export")
    public void exportData(HttpServletResponse response, Order order, String name, String province, Integer status, String startTime, String endTime) {
        name = UF.toString(name);
        province = UF.toString(province);
        startTime = UF.toString(startTime);
        endTime = UF.toString(endTime);
        status = status == null ? -1 : status;
        List<GoldShop> list = goldShopService.listRecords(name, province, status, startTime, endTime, order.getOrder(), order.getSort(), 0, 0);
        if (list == null) {
            list = new ArrayList<GoldShop>();
        }
        String fileName = "门店管理";
        String[] columnNames = { "序号", "门店名称", "所属省份", "状态", "创建时间", "创建人"};
        String[] columns = {"index",  "name", "province", "statusMark", "addTime", "createName"};
        int index = 1;
        for (GoldShop bean : list) {
            bean.setIndex(index);
            index++;
            if (bean.getStatus() == 0) {
                bean.setStatusMark("关闭");
            } else if (bean.getStatus() == 1) {
                bean.setStatusMark("开启");
            }
        }
        ExportExcelController<GoldShop> export = new ExportExcelController<GoldShop>();
        export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    @GetMapping(value = "/display")
    public SerializeObject<List<GoldShopBean>> listForDisplay(BigDecimal longitude, BigDecimal latitude) {
        if (longitude == null || latitude == null) {
            return new SerializeObjectError("00000002");
        }
        List<GoldShopBean> shopBeans = goldShopService.queryForDisplay();
        if (shopBeans != null && shopBeans.size() > 0) {
            for (GoldShopBean bean : shopBeans) {
                bean.setDistance(LocationUtil.getDistance(latitude.doubleValue(), longitude.doubleValue(), bean.getLatitude().doubleValue(), bean.getLongitude().doubleValue()));
            }
            Collections.sort(shopBeans,new Comparator<GoldShopBean>(){
                @Override
                public int compare(GoldShopBean o1, GoldShopBean o2) {
                    if (o1.getDistance() > o2.getDistance()) {
                        return 1;
                    } else if (o1.getDistance() == o2.getDistance()) {
                        return 0;
                    }
                    return -1;
                }
            });
        }
        return new SerializeObject<>(ResultType.NORMAL, shopBeans);
    }
    @GetMapping(value = "/detail")
    public SerializeObject<GoldShopBean> getShopDetail(int id) {
        if (id < 1) {
            return new SerializeObjectError("00000002");
        }
        return new SerializeObject<>(ResultType.NORMAL, goldShopService.getShop(id));
    }


    protected String invokeHttp(String url, List<NameValuePair> nvps) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            if(nvps != null && nvps.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            }
            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if(statusCode == 200) {
                return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            }
        } catch (IOException e) {
            getLog().error(e.getMessage());
        } finally {
            httpPost.releaseConnection();
        }

        return null;
    }
}
